<template>
  <div class="bonus_add">
    <div class="bonus_add_main">
      <div class="bonus_add_l">
        <el-form ref="dataForm" :model="form" :rules="rules">
          <div>
            <div class="bonus_item1_select_tips">*申请季度</div>
            <el-select size="small" v-model="quartYM" value-key="name" placeholder="请选择" @change="changeYearQuater">
              <el-option v-for="item in yearQuater" :key="item.name" :label="item.name" :value="item"></el-option>
            </el-select>
          </div>
          <div>
            <div class="bonus_item1_select_tips">*具体人员</div>
            <el-form-item prop="personId" size="small" class="select_person">
              <el-select filterable v-model="form.personId" placeholder="请选择人员" clearable @change="changePerson">
                <el-option
                  v-for="item in columnsPeoples"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="bonus_item1_select_tips">* {{ activeOne === '1' ? '加' : '减' }}分项分类</div>
          <div class="bonus_item1_select_name">
            <div
              class="bonus_item1_select_pad"
              v-for="item in levelOption1"
              :key="item.id"
              :class="{ active_select1: item.id == category1 }"
              @click="cliSelect1(item, '1')">
              <span>{{ item.label }}</span>
            </div>
          </div>
          <div class="bonus_item1_select_tips" v-if="levelOption2.length > 0">* {{ titleTwo }}</div>
          <div class="bonus_item1_select_name">
            <div
              class="bonus_item1_select_pad"
              v-for="item in levelOption2"
              :key="item.id"
              :class="{ active_select1: item.id == category2 }"
              @click="cliSelect1(item, '2')">
              <span>{{ item.label }}</span>
            </div>
          </div>
          <div class="bonus_item1_select_tips" v-if="levelOption3.length > 0">* {{ level3Name }}</div>
          <div class="bonus_item1_select_name">
            <div
              class="bonus_item1_select_pad"
              v-for="item in levelOption3"
              :key="item.id"
              :class="{ active_select1: item.id == category3 }"
              @click="cliSelect1(item, '3')">
              <span>{{ item.label }}</span>
            </div>
            <span
              class="tips_r"
              v-if="category3 == '5-02-01-01' || category3 == '5-02-02-01' || category3 == '5-02-03-01'">
              提示：
              <span class="tips_r_color">请在证明材料处上传领导批示的证明材料！</span>
            </span>
          </div>
          <div v-if="!((level3Name == '加分项名称' || level3Name == '减分项名称') && level3Option != '其他')">
            <div class="bonus_item1_select_tips">* {{ activeOne === '1' ? '加' : '减' }}分项名称</div>
            <el-form-item prop="boundsName">
              <el-input
                type="textarea"
                maxlength="200"
                placeholder="填写该加分项的具体名称或简要描述，例如市级先进基层党组织"
                v-model="form.boundsName"></el-input>
            </el-form-item>
          </div>
          <div class="bonus_item1_select_tips all_tips">* {{ activeOne === '1' ? '加' : '减' }}分项说明</div>
          <el-form-item class="m-b-1" prop="boundsRemark">
            <el-input
              type="textarea"
              maxlength="100"
              placeholder="对该加分项的详细解释说明，例如xx党支部受xx表彰，获评xx年度市级先进基层党组织"
              v-model="form.boundsRemark"></el-input>
          </el-form-item>

          <div class="bonus_item1_select_tips all_tips">证明材料</div>
          <el-form-item
            prop="albumList"
            :class="
              category3 == '5-02-01-01' || category3 == '5-02-02-01' || category3 == '5-02-03-01'
                ? 'file_item'
                : 'file_item_nomal'
            ">
            <UploadFile
              :file-list="form.albumList"
              @saveFileData="saveFileData"
              :titleAdd="
                category3 == '5-02-01-01' || category3 == '5-02-02-01' || category3 == '5-02-03-01'
                  ? '媒体报道材料：'
                  : ''
              ">
              <div class="file_tips" slot="other">
                <div class="tip_li">此处请上传{{ activeOne === '1' ? '加' : '减' }}分项相关证明材料</div>
              </div>
            </UploadFile>
          </el-form-item>
          <div class="bonus_item1_select_tips all_tips">*评分</div>
          <div class="board_list_score">
            <p>{{ info.ramarkCalcRule }}</p>
            <div class="board_score_fix">
              <div class="bonus_time">
                <div class="board_score_num">{{ info.indexPoint }}</div>
                <span class="board_score_num_r">分</span>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <div class="bonus_add_r">
        <div class="add_r_title m-b-1">{{ activeOne === '1' ? '加' : '减' }}分构成说明</div>
        <div class="m-b-1" v-for="(mark, index) in remarkList" :key="index">
          <span class="add_r_title">{{ index + 1 }}.{{ mark.title }}：</span>
          <span>{{ mark.ramarkCalcRuleShow }}</span>
        </div>
      </div>
    </div>
    <div class="btn_save">
      <el-button size="small" @click="cancelBtn">取 消</el-button>
      <el-button size="small" type="primary" @click="insertData(0)">提交</el-button>
      <el-button size="small" type="primary" @click="insertData(1)">提交并录入下一个</el-button>
    </div>
  </div>
</template>

<script>
import UploadFile from '@com/UploadFile'
import {
  listIndexList,
  inputBonusPoints,
  getBonusPointsDetails,
  getSelectAllDepartment,
  getselectAllUserByDepartment,
  getListAllUserByOrgId,
  selectYearAndQuarter,
} from '@apis/bonus.js'
export default {
  components: {
    UploadFile,
  },
  props: {
    // 1申报、2审核、3考核办
    bonusType: {
      type: String,
      default: '1',
    },
    id: {
      type: String,
      default: '',
    },
    statusTable: {
      type: String,
      default: '',
    },
    // 1申请个人加分项；2考核办为个人录入加分项；3考核办为部门录入加分项；4申请部门加分项；5考核办为个人录入减分项；6考核办为部门录入减分项
    newType: {
      type: String,
      default: '1',
    },
    processInstanceId: {
      type: String,
      default: '',
    },
    taskId: {
      type: String,
      default: '',
    },
    activeOne: {
      type: String,
      default: '1',
    },
  },
  data() {
    const validScore = (rule, value, callback) => {
      if (!this.score) {
        callback(new Error('请输入分数'))
      } else {
        const scoreInput = Number(this.score)
        const maxScore = Number(this.info.maxScore)
        const minScore = Number(this.info.minScore)
        if (scoreInput > maxScore || scoreInput < minScore) {
          callback(new Error('请输入正确分值'))
        } else {
          callback()
        }
      }
    }
    // const validFile = (rule, value, callback) => {
    //   if (value && value.length > 0) {
    //     callback()
    //   } else {
    //     callback(new Error('请上传附件'))
    //   }
    // }
    return {
      userInfo: JSON.parse(localStorage.PSKH_USERINFO),
      levelOption1: [], // 加分项分类
      category1: '', // 加分项分类id
      levelOption2: [], // 加分项级别
      category2: '', // 加分项级别id
      levelOption3: [], // 三级分类
      category3: '',
      level3Name: '',
      level3Option: '',
      form: {
        boundsName: '', // 加分项名称
        boundsRemark: '', // 加分项说明
        albumList: [], // 证明材料
        commentList: [],
        enclosureList: [], //
        organId: '', // 科室
        personId: '', // 科室人员
        times: 1,
        headCount: 1,
        boundsYear: '',
        boundsQuarter: '',
      },
      checkData: {
        checked1: false,
        checked2: false,
        check1Name: '窗口单位主要领导每月到窗口调研（坐班）',
        check2Name: '窗口工作人员有被提拔使用的（提供相关文件，含职级晋升）',
        check3Name: '办事企业和群众主动评价为“不满意”或“非常不满意”（含书面批评）的',
        check4Name: '对主动评价中有弄虚作假行为，经提醒后不予改正的',
        check5Name: '窗口工作人员被提拔使用（含职级晋升）',
      },
      rules: {
        organId: [{ required: true, message: '请选择科室', trigger: 'change' }],
        personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
        boundsName: [{ required: true, message: '请填写名称', trigger: 'blur' }],
        boundsRemark: [{ required: true, message: '请填写说明', trigger: 'blur' }],
        score: [{ required: true, validator: validScore, trigger: 'blur' }],
        // albumList: [{ required: true, validator: validFile, trigger: 'change' }],
        // commentList:[{ required: true, validator: validFile, trigger: 'change' }],
        times: [{ required: true, message: '请输入次数', trigger: 'change' }],
        headCount: [{ required: true, message: '请输入人数', trigger: 'change' }],
      },
      stateList: [
        { id: '0', name: '不通过' },
        { id: '1', name: '通过' },
      ],
      info: {},
      score: '',
      scoreLow: 1, // 输入减分
      columnsOffices: [],
      columnsPeoples: [],
      titleTwo: '加分项级别',
      remarkList: [],
      quartYM: {},
      yearQuater: [],
    }
  },
  created() {
    this.selectYearAndQuarter()
    this.getBonusList1() // 获取枚举选项
    this.getListAllUserByOrgId()
    this.titleTwo = this.activeOne === '1' ? '加分项级别' : '减分项级别'
  },
  mounted() {},
  methods: {
    removeHtmlStyle(html) {
      const rel = /style\s*?=\s*?([‘"])[\s\S]*?\1/g
      let newHtml = ''
      if (html) {
        newHtml = html.replace(rel, '')
      }
      return newHtml
    },
    // 一级加分项
    async getBonusList1() {
      const userID = this.newType === '1' ? this.userInfo.userId : ''
      const organId = this.userInfo.loginPostInfo.orgId
      this.levelOption1 = await this.listIndexList(
        '',
        0,
        this.form.personId || userID,
        this.id,
        this.form.organId || organId
      )
      this.remarkList = []
      for (const i in this.levelOption1) {
        this.remarkList.push({
          title: this.levelOption1[i].label,
          ramarkCalcRuleShow: this.levelOption1[i].ramarkCalcRuleShow,
        })
      }
      if (this.statusTable === '0') {
        this.levelOption1.forEach((el, index) => {
          if (el.isChoose) {
            this.category1 = el.id
          }
        })
      } else {
        this.info = this.levelOption1[0]
        this.category1 = this.levelOption1[0].id
      }
      this.getBonusList2(this.category1)
    },
    // 二级加分项
    async getBonusList2(code) {
      this.levelOption2 = await this.listIndexList(code, 1, '', this.id, '')
      if (this.levelOption2.length > 0) {
        if (this.statusTable === '3') {
          this.levelOption2.forEach((el, index) => {
            if (el.isChoose) {
              this.category2 = el.id
            }
          })
          if (this.category2 === '') {
            this.info = this.levelOption2[0]
            this.category2 = this.levelOption2[0].id
          }
        } else {
          this.info = this.levelOption2[0]
          this.category2 = this.levelOption2[0].id
        }
        this.getBonusList3(this.category2)
      } else {
        this.category2 = ''
      }
    },
    // 三级加分项
    async getBonusList3(code) {
      this.levelOption3 = await this.listIndexList(code, 1, '', this.id, '')
      if (this.levelOption3.length > 0) {
        if (this.statusTable === '3') {
          this.levelOption3.forEach((el, index) => {
            if (el.isChoose) {
              this.category3 = this.levelOption3[index].id
              this.level3Name = this.levelOption3[index].remark
              this.level3Option = this.levelOption3[index].label
            }
          })
          if (this.category3 === '') {
            this.info = this.levelOption3[0]
            this.category3 = this.levelOption3[0].id
            this.level3Name = this.levelOption3[0].remark
            this.level3Option = this.levelOption3[0].label
          }
        } else {
          this.info = this.levelOption3[0]
          this.category3 = this.levelOption3[0].id
          this.level3Name = this.levelOption3[0].remark
          this.level3Option = this.levelOption3[0].label
        }
      } else {
        this.category3 = ''
        this.level3Option = ''
      }
    },
    // 类别枚举-获取指标项
    listIndexList(pcode, type, userId, id, organId) {
      return new Promise((resolve, reject) => {
        listIndexList({
          indexType: this.activeOne,
          pcode: pcode,
          type: type,
          userId: userId,
          id: id,
          organId: organId,
        })
          .then(res => {
            resolve(res.data)
          })
          .catch(() => {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject([])
          })
      })
    },
    // 点击类别
    cliSelect1(item, type) {
      this.clearSpecialData()
      this.info = item
      if (type === '1') {
        this.category1 = item.id
        this.getBonusList2(item.id)
        this.category2 = ''
        this.category3 = ''
        this.level3Name = ''
        this.levelOption2 = []
        this.levelOption3 = []
        this.titleTwo = item.label === '便民服务' ? '服务类别' : this.activeOne === '1' ? '加分项级别' : '减分项级别'
      } else if (type === '2') {
        this.category2 = item.id
        this.category3 = ''
        this.level3Name = ''
        this.getBonusList3(item.id)
        this.levelOption3 = []
      } else if (type === '3') {
        this.category3 = item.id
        this.level3Name = item.remark
        this.level3Option = item.label
      }
    },

    // 获取所有科室
    getDepart() {
      getSelectAllDepartment({}).then(res => {
        if (res.status === 200) {
          this.columnsOffices = res.data
        }
      })
    },
    changeDepart() {
      this.form.personId = ''
      if (this.form.organId) {
        this.getselectAllUserByDepartment(this.form.organId)
      } else {
        this.columnsPeoples = []
      }
    },
    changePerson() {
      // this.getBonusList1() //获取枚举选项
    },
    getselectAllUserByDepartment(id) {
      // 获取所有科室
      getselectAllUserByDepartment({
        id: id,
      }).then(res => {
        if (res.status === 200) {
          this.columnsPeoples = res.data
        }
      })
    },
    // 去除验证
    saveFileData() {
      this.$refs.dataForm.validate(valid => {
        if (!valid) {
          return false
        }
      })
    },

    // 取消
    cancelBtn() {
      this.$emit('cancelData', true)
    },
    // 考核办录入
    insertData(saveStatus) {
      this.$refs.dataForm.validate(valid => {
        if (!valid) {
          return false
        } else {
          this.departInsert(saveStatus)
        }
      })
    },
    // 考核办录入
    departInsert(saveStatus) {
      const score = this.info.optionType === 'fixed_score' ? this.info.indexPoint : this.score
      const headCount = ''
      const times = ''
      const bonusName = ''
      inputBonusPoints({
        orgId: this.form.organId,
        userId: this.form.personId,
        boundsName: this.form.boundsName || this.level3Option || bonusName, // 加分项名称
        boundsRemark: this.form.boundsRemark, // 加分项说明
        boundsType: this.category3 || this.category2 || this.category1, // 加分项类别code
        albumList: this.form.albumList, // 相册
        commentList: this.form.commentList,
        enclosureList: this.form.enclosureList, // 附件
        score: score,
        times: times,
        headCount: headCount,
        applyType: this.activeOne === '1' ? '2' : '5',
        boundsYear: parseFloat(this.form.boundsYear),
        boundsQuarter: parseFloat(this.form.boundsQuarter),
      }).then(res => {
        if (res.status === 200) {
          this.$message({
            message: res.message,
            type: 'success',
          })
          if (saveStatus === 0) {
            this.$emit('addSuccess', true)
          } else {
            this.$emit('addSuccess', false)
            this.clearData()
          }
        }
      })
    },
    clearData() {
      this.form = {
        boundsName: '', // 加分项名称
        boundsRemark: '', // 加分项说明
        albumList: [], // 证明材料
        commentList: [],
        enclosureList: [], //
        organId: '', // 科室
        personId: '', // 科室人员
        times: 1,
        headCount: 1,
        boundsYear: this.quartYM.year,
        boundsQuarter: this.quartYM.quater,
      }
      this.score = ''
      this.info.indexPoint = this.info.indexPointFormula
      this.checkData.checked1 = false
      this.checkData.checked2 = false
      this.scoreLow = 1
    },
    // 清除特殊数据
    clearSpecialData() {
      this.checkData.checked1 = false
      this.checkData.checked2 = false
      this.form.times = 1
      this.form.headCount = 1
      this.info.indexPoint = this.info.indexPointFormula
      this.scoreLow = 1
      this.score = ''
    },

    // 获取待修改信息
    getApplyParmas() {
      getBonusPointsDetails({
        id: this.id,
      }).then(res => {
        if (res.status === 200) {
          this.form = { ...res.data }
        }
      })
    },

    changeTime(nowValue, type) {
      nowValue = nowValue ? parseInt(nowValue) : 1
      this.form.times = nowValue
      if (nowValue <= 0) {
        this.form.times = 1
      }
    },
    changeMan(nowValue, type) {
      nowValue = nowValue ? parseInt(nowValue) : 1
      this.form.headCount = nowValue
      if (nowValue <= 0) {
        this.form.headCount = 1
      }
      if (type === '2') {
        const timeScore = this.checkData.checked1 ? this.form.times * 1 : 0
        this.info.indexPoint = this.form.headCount * 0.5 + timeScore
      }
    },
    // 单位重视的处理
    changeCheck(type) {
      if (type === '1') {
        const manScore = this.checkData.checked2 ? this.form.headCount * 0.5 : 0
        if (this.checkData.checked1) {
          this.info.indexPoint = this.form.times * 1 + manScore
        } else {
          this.info.indexPoint = manScore
        }
      } else if (type === '2') {
        const timeScore = this.checkData.checked1 ? this.form.times * 1 : 0
        if (this.checkData.checked2) {
          this.info.indexPoint = this.form.headCount * 0.5 + timeScore
        } else {
          this.info.indexPoint = timeScore
        }
      } else if (type === '3') {
        if (this.checkData.checked1) {
          this.info.indexPoint = this.form.times * 0.5
          if (this.info.indexPoint > 1) {
            this.info.indexPoint = 1
          }
        } else {
          this.info.indexPoint = 0
        }
      }
    },
    changeLow(nowValue) {
      nowValue = nowValue || 1
      if (nowValue < 1) {
        nowValue = 1
      } else if (nowValue > 2) {
        nowValue = 2
      }
      this.scoreLow = nowValue
    },

    stopScrollFun(evt) {
      evt = evt || window.event
      if (evt.preventDefault) {
        evt.preventDefault()
        evt.stopPropagation()
      } else {
        evt.cancelBubble = true
        evt.returnValue = false
      }
      return false
    },
    getListAllUserByOrgId() {
      getListAllUserByOrgId({ id: this.userInfo.loginPostInfo.orgId }).then(res => {
        if (res.status === 200) {
          this.columnsPeoples = res.data
        }
      })
    },
    changeYearQuater() {
      this.form.boundsYear = this.quartYM.year
      this.form.boundsQuarter = this.quartYM.quater
    },
    selectYearAndQuarter() {
      selectYearAndQuarter({
        id: '2',
      }).then(res => {
        if (res.status === 200) {
          const listQuater = res.data
          this.yearQuater = []
          if (listQuater.length > 0) {
            for (const i in listQuater) {
              const year = listQuater[i].year
              for (const j in listQuater[i].list) {
                let quater = '第一季度'
                if (listQuater[i].list[j].quarter === 1) {
                  quater = '第一季度'
                } else if (listQuater[i].list[j].quarter === 2) {
                  quater = '第二季度'
                } else if (listQuater[i].list[j].quarter === 3) {
                  quater = '第三季度'
                } else if (listQuater[i].list[j].quarter === 4) {
                  quater = '第四季度'
                }
                this.yearQuater.push({
                  year: year,
                  name: `${year}年${quater}`,
                  quater: listQuater[i].list[j].quarter,
                  isChoose: listQuater[i].list[j].isChoose,
                })
              }
            }
            for (let i = 0; i < this.yearQuater.length; i++) {
              if (this.yearQuater[i].isChoose) {
                this.quartYM = this.yearQuater[i]
                this.form.boundsYear = this.quartYM.year
                this.form.boundsQuarter = this.quartYM.quater
                break
              }
            }
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.bonus_add {
  // padding: 10px;
  height: 100%;
  overflow-y: auto;
  /deep/ .el-form-item__error {
    padding-top: 1px;
  }
  .file_item {
    /deep/ .el-form-item__error {
      padding-left: 120px;
      margin-top: -20px;
    }
  }
  .file_item_nomal {
    /deep/ .el-form-item__error {
      margin-top: -20px;
    }
  }
  .bonus_add_main {
    display: flex;
    border-bottom: 1px solid #ececec;
  }
  .top_chench {
    padding-bottom: 10px;
    border-bottom: 1px solid #ececec;
    margin-bottom: 10px;
  }
  .color_tips {
    color: #a7a7a7;
  }
  .numbers_item {
    display: flex;
    align-items: center;
    margin-top: 10px;
    span {
      margin-right: 10px;
    }
    .time_item {
      width: 150px;
      margin-right: 10px;
    }
  }

  .tt_item {
    margin-right: 10px;
    width: 170px;
    /deep/ .el-input__inner {
      height: 40px;
    }
  }
  .bonus_add_l {
    width: 65%;
    padding: 0 20px;
    .select_depart {
      display: inline-block;
    }
    .select_person {
      display: inline-block;
      // margin-left: 20px;
    }
    .bonus_item1_select_tips {
      margin: 10px 0;
      color: #333;
      font-size: 14px;
      font-weight: bold;
    }
    .all_tips {
      margin-top: 15px;
    }
    .bonus_item1_select_name {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    .bonus_item1_select_pad {
      padding: 10px;
      margin: 5px 12px 5px 0;
      border-radius: 4px;
      cursor: pointer;
      background-color: #f4f4f4;
      color: #333;
    }
    .active_select1 {
      background-color: #004db6;
      color: #fff;
    }
    .file_tips {
      font-size: 14px;
      color: #8f939a;
      margin-left: 10px;
      margin-top: -4px;
    }
    .tips_r {
      display: inline-block;
      margin-top: 15px;
      .tips_r_color {
        color: #a7a7a7;
      }
    }
    .board_list_score {
      line-height: 30px;
      // border: 2px solid #eee;
      p {
        font-size: 14px;
        padding: 0 10px;
        background-color: #f9f9f9;
      }
      .board_score_fix {
        margin: 10px 0;
        font-size: 16px;
        display: flex;
      }
      .bonus_time {
        display: flex;
        width: 100%;
      }
      .board_score_num {
        line-height: 36px;
        width: 40%;
        text-align: center;
        border: 2px solid #004db6;
      }
      .board_score_cancel {
        line-height: 36px;
        text-align: center;
        height: 36px;
        margin-left: 10px;
        color: #ff0000;
      }
      .size_input {
        /deep/ .el-input__inner {
          height: 36px;
        }
        ::-webkit-outer-spin-button,
        ::-webkit-inner-spin-button {
          margin: 0;
          -webkit-appearance: none !important;
        }

        input[type='number']::-webkit-outer-spin-button,
        input[type='number']::-webkit-inner-spin-button {
          margin: 0;
          -webkit-appearance: none !important;
        }
      }
      .board_score_num_r {
        line-height: 36px;
        width: 50px;
        text-align: center;
        display: inline-block;
        border: 2px solid #004db6;
        border-left: none;
        background-color: #e9eff48f;
      }
    }
  }
  .bonus_add_r {
    width: 35%;
    background-color: #f2f2f2;
    padding: 10px;
    line-height: 25px;
    color: #a7a7a7;
    .add_r_title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  .btn_save {
    margin-top: 10px;
    text-align: right;
    padding-right: 10px;
  }
  .bonus_item1_select_back {
    line-height: 26px;
    margin-bottom: 10px;
    color: #666666;
    width: 100%;
    padding: 5px 10px;
    background-color: #e9eff48f;
    white-space: pre-wrap;
  }
}
</style>
